﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Text;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class wsBase : System.Web.Services.WebService
{


    public class XDCode
    {
        //고객정보
        public string CodeID;
        public string CodeNAME;

    }

    public XDCode[] Table2Code(DataSet ds)
    {
        XDCode[] Codes = new XDCode[ds.Tables[0].Rows.Count];
        int curr = 0;
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            XDCode code = new XDCode();
            code.CodeID = dr["code"].ToString();
            code.CodeNAME = dr["name"].ToString();
            Codes[curr] = code;
            curr++;
        }

        return Codes;

    }

    private XDCode SetXDCode(string Code, string Name)
    {
        XDCode oCode = new XDCode();
        oCode.CodeID = Code;
        oCode.CodeNAME = Name;
        return oCode;
    }

    [WebMethod]
    public XDCode[] GetTest()
    {
        XDCode[] Codes = new XDCode[7];


        Codes[0] = SetXDCode("010", "010");
        Codes[1] = SetXDCode("011", "011");
        Codes[2] = SetXDCode("016", "016");
        Codes[3] = SetXDCode("017", "017");
        Codes[4] = SetXDCode("018", "018");
        Codes[5] = SetXDCode("019", "019");
        Codes[6] = SetXDCode("0130", "0130");

        return Codes;
    }

    [WebMethod]
    public string GetJson()
    {
        string Codes = "{'name':'kkk'}";

        return Codes;
    }

    public wsBase()
    {

        //디자인된 구성 요소를 사용하는 경우 다음 줄의 주석 처리를 제거합니다. 
        //InitializeComponent(); 
    }



    /// <summary>
    /// 내    용 : Schema의 해당하는 Row에 값 저장 
    /// 작 성 자 : 김성민
    /// 작 성 일 : 2005-07-20
    /// </summary>
    /// <param name="obj">XML Schema</param>
    /// <param name="dt">실행 결과 XML Scheam</param>
    /// <param name="idx">index</param>
    /// <returns></returns>
    public void RowBind(object obj, DataTable dt, int idx)
    {
        if (dt.Rows.Count > 0)
        {
            Type ty = obj.GetType();
            FieldInfo[] finfo = ty.GetFields();

            string rowType;
            foreach (FieldInfo fi in finfo)
            {
                if (dt.Columns.IndexOf(fi.Name) >= 0)
                {
                    rowType = dt.Rows[idx][fi.Name].GetType().ToString();

                    if (dt.Rows[idx][fi.Name].GetType().ToString() != "System.DBNull")

                        fi.SetValue(obj, dt.Rows[idx][fi.Name].ToString());

                    /*
                    if (rowType != "System.DBNull")
                    {
                        if (rowType == "System.String")  fi.SetValue(obj, dt.Rows[idx][fi.Name].ToString());
                        else if (rowType == "System.Int16")   fi.SetValue(obj, (int)dt.Rows[idx][fi.Name]);
                        else if (rowType == "System.Int32")   fi.SetValue(obj, (int)dt.Rows[idx][fi.Name]);
                    }
                    */
                }
            }
        }
    }

    /// <summary>
    /// 내    용 :
    /// 작 성 자 : 김성민
    /// 작 성 일 : 2005-07-20
    /// </summary>
    /// <param name="dt">실행 결과 DataTable형태</param>
    /// <param name="obj">XML Scheam 배열형태</param>
    /// <param name="item">XML Scheam</param>
    /// <returns></returns>
    public object[] TableBind(DataTable dt, object[] obj, object item)
    {
        Type tyi = item.GetType();

        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                int loop = 0;
                for (loop = 0; loop < dt.Rows.Count; loop++)
                {
                    obj[loop] = Activator.CreateInstance(tyi);
                    this.RowBind(obj[loop], dt, loop);
                }
            }
        }
        return obj;
    }


    /// <summary>
    /// //exec USPTotalSearch "cstid, cstname", "tb100010" , "cstname = '김성민'", "cstname", 10, 0
    /// </summary>
    /// <param name="조회필드">cstid, cstname</param>
    /// <param name="대상테이블">tb100010</param>
    /// <param name="조건식">where cstname = '김성민'</param>
    /// <param name="정렬순서">order by cstname</param>
    /// <param name="페이지단위">10</param>
    /// <param name="조회페이지">0</param>
    /// <returns></returns>
    /// 
    public DataSet PageView(string 조회필드, string 대상테이블, string 조건식, string 정렬순서, int 페이지단위, int 조회페이지)
    {
        //exec USPTotalSearch "cstid, cstname", "tb100010" , "cstname = '김성민'", "cstname", 10, 0

        string SqlComm = string.Format(@"
            DECLARE @시작번호   INT  
            DECLARE @총자료수   INT  
            DECLARE @총페이지수 INT  
            DECLARE @조회페이지 INT  
            DECLARE @페이지단위 INT  

            SET @조회페이지 = {5} 
            SET @페이지단위 = {4}

            SELECT 1 AS _COL INTO #_TEMP  
            SELECT @총자료수 = COUNT(*)   FROM {1}  /* WHERE */ {2}

            SELECT @총페이지수 = ((@총자료수-1) / @페이지단위)+1  
             IF  @조회페이지 >= 1 and @조회페이지 < @총페이지수 +1   
              BEGIN    
	            SELECT *,  IDENTITY(INT,1,1) AS _ID INTO #TMPSEEK11     
	            FROM ( 
                        SELECT TOP {7} {0} FROM {1}, #_TEMP /* WHERE */ {2}/* ORDER BY */ {3}
	                  ) A     

	            SELECT TOP {4} * FROM #TMPSEEK11 WHERE _ID >= {6} ORDER BY _ID    

	            SELECT @총자료수 AS TRCOUNT,@총페이지수 AS TPCOUNT, @조회페이지 AS VIEWPAGE,1 AS TYPE     
               END  
            else  
              BEGIN      
                          SELECT TOP 0  {0}, 0 AS _ID  FROM {1}
                          
                         SELECT @총자료수 AS TRCOUNT,@총페이지수 AS TPCOUNT, @조회페이지 AS VIEWPAGE, -1 AS TYPE     
            END 
         ", 조회필드, 대상테이블, 조건식, 정렬순서, 페이지단위, 조회페이지, (조회페이지 - 1) * 페이지단위 + 1, @페이지단위 * (@조회페이지));


        DataSet ds = DbObject.ExecuteDataset(DbObject.CONN_STRING, CommandType.Text, SqlComm);

        return ds;



    }

    public string GetJSONString(DataTable Dt, string TRCOUNT, string TPCOUNT, string VIEWPAGE)
    {
        StringBuilder Sb = new StringBuilder();
        Sb.Append("{\"Records\" : [");
        for (int i = 0; i < Dt.Rows.Count; i++)
        {
            string TempStr = "";
            Sb.Append("{");
            for (int j = 0; j < Dt.Columns.Count; j++)
            {
                // 향후 테이블 타입에 대한 정의가 필요하며
                // 웹 특수문자에 대한 대응도 필요함
                if (!System.DBNull.Value.Equals(Dt.Rows[i][j]))
                {
                    TempStr += TempStr == string.Empty ? "" : ",";
                    string FldData = Dt.Rows[i][j].ToString();
                    FldData = FldData.Replace("\n", "&#13;");

                    switch (Dt.Columns[j].DataType.Name)
                    {
                        case "DateTime":
                            TempStr += "\"" + Dt.Columns[j].Caption + "\" : \"" + FldData.Substring(0, 10) + "\"";
                            break;
                        default:
                            TempStr += "\"" + Dt.Columns[j].Caption + "\" : \"" + FldData.ToString() + "\"";
                            break;
                    }

                }
            }
            Sb.Append(TempStr + "},");
        }

        if (System.Convert.ToInt32(TRCOUNT) > 0)
        {
            Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
        }
        string ttt = string.Format("], \"TRCOUNT\" : \"{0}\", \"TPCOUNT\" : \"{1}\", \"VIEWPAGE\" : \"{2}\", \"UserData\" : \"대한민국\" ", TRCOUNT, TPCOUNT, VIEWPAGE);
        Sb.Append(ttt);
        Sb.Append("}");

        return Sb.ToString();
    }


}

